{% extends "base.html" %}

{% block title %}BunnySpell - {{ game_title }}{% endblock %}

{% block styles %}
<link href="https://fonts.googleapis.com/css2?family=Fredoka+One&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Fredoka&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{{ url_for('static', filename='game_spell.css') }}">
{% endblock %}

{% block content %}
<!-- 在 body 标签的开始处添加这行 -->
<div id="blur-overlay"></div>

<h1 class="game-title">{{ game_title }}</h1>
<div id="remaining-words" class="remaining-words">Remaining Words: {{ words|length }}</div>
<div id="score">Score: 0</div>
<div id="aichat-container">
</div>
<div class="game-content">
    <div id="word-display">HELLO</div>
    <div id="input-container"></div>
    <button id="skip-button" class="skip-button">SKIP</button>
</div>
<div id="wordlist-container" style="display: none;">
    <div class="wordlist-column">
        <ul id="word-results"></ul>
    </div>
</div>
<div id="final-score"></div>
<div id="completion-image" class="completion-image"></div>
<button id="start-game-button" onclick="startGame()">Start Game</button>

<script>
    // 使用 Jinja2 将 word_dict 渲染到前端
    const wordDictionary = JSON.parse('{{ word_dict | tojson | safe }}');
    const game_id = '{{ game_id }}';
    // 从 wordDictionary 中获取所有单词
    const words = Object.keys(wordDictionary);

    console.log(wordDictionary);
    console.log(words);
 
    const wordDisplay = document.getElementById("word-display");
    const inputContainer = document.getElementById("input-container");
    const scoreDisplay = document.getElementById("score");
    let score = 0;
    let wordIndex = 0;

    // 初始化单词
    let totalAttempts = 0;
    let correctAttempts = 0;

    let currentWord = '';
    let correctLetters = [];  // 新增：用于跟踪已正确输入的字母

    let wordResults = {};
    let completionRate = 0;
    let completedWords = 0;  // New variable to track completed words

    let autoPlayEnabled = false;

    // 修改 playAudioTwice 函数
    function playAudioTwice(audioUrl) {
        const audio = new Audio(audioUrl);
        let playCount = 0;

        // 获取当前单词的音频图标元素
        const iconElement = document.querySelector('.audio-icon');

        function playWithAnimation() {
            iconElement.classList.add('playing');
            
            audio.play().catch(error => console.log("Playback prevented:", error));
            
            audio.onended = function() {
                iconElement.classList.remove('playing');
                playCount++;
                if (playCount < 2) {
                    setTimeout(playWithAnimation, 1000); // 1秒后播放第二次
                }
            };
        }

        playWithAnimation();
    }

    function initializeWord() {
        if (wordIndex >= words.length) {
            completionRate = (completedWords / words.length).toFixed(2);
            scoreDisplay.innerText = `Score: ${score} | Completion Rate: ${(completionRate * 100).toFixed(1)}%`;
            endGame();
            return;
        }
        
        // Add this line to update remaining words
        document.getElementById('remaining-words').innerText = `Remaining Words: ${words.length - wordIndex}`;
        
        inputContainer.innerHTML = "";
        currentWord = words[wordIndex];
        correctLetters = new Array(currentWord.length).fill(false);
        
        // 显示单词的含义和例句
        wordDisplay.innerHTML = `
            <div class="word-meaning">
                ${wordDictionary[currentWord].meaning} 
                <span class="word-phonetic">
                    (${wordDictionary[currentWord].pronunciation})
                    <span class="audio-icon" onclick="playAudio('${wordDictionary[currentWord].audio}', this)">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                            <polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5" class="speaker"></polygon>
                            <path d="M15.54 8.46a5 5 0 0 1 0 7.07" class="wave1"></path>
                            <path d="M19.07 4.93a10 10 0 0 1 0 14.14" class="wave2"></path>
                        </svg>
                    </span>
                </span>
            </div>
            <div class="word-example">${wordDictionary[currentWord].example.replace(currentWord, '[ ]')}</div>
        `;

        // 只有在启用自动播放后才自动播放读音
        if (autoPlayEnabled && wordDictionary[currentWord].audio) {
            setTimeout(() => {
                playAudioTwice(wordDictionary[currentWord].audio);
            }, 500); // 稍微延迟一下，确保 DOM 已经更新
        }

        // 创建输入框
        for (let i = 0; i < currentWord.length; i++) {
            const inputBox = document.createElement("input");
            inputBox.type = "text";
            inputBox.maxLength = 1;
            inputBox.classList.add("letter-input");
            inputBox.dataset.index = i;
            inputContainer.appendChild(inputBox);
            
            inputBox.addEventListener("input", function(event) {
                const input = event.target;
                const letter = input.value.toUpperCase();
                const index = parseInt(input.dataset.index);
                
                // 只允许英文字母
                if (!/^[A-Z]$/.test(letter)) {
                    input.value = '';
                    return;
                }

                const correctLetter = currentWord[index].toUpperCase();
                
                if (letter === "") {
                    input.value = '';
                    return;
                }

                if (letter === correctLetter) {
                    event.target.classList.remove("incorrect");
                    event.target.classList.add("correct");
                    
                    if (!correctLetters[index]) {
                        correctLetters[index] = true;
                        correctAttempts++;
                        totalAttempts++;
                    }
                    
                    if (correctLetters.every(letter => letter === true)) {
                        score++;
                        completionRate = (completedWords / words.length).toFixed(2);
                        scoreDisplay.innerText = `Score: ${score} | Completion Rate: ${(completionRate * 100).toFixed(1)}%`;
                    }
                    
                    if (index < currentWord.length - 1) {
                        inputContainer.children[index + 1].focus();
                    } else {
                        setTimeout(() => {
                            showCompletedWord();
                        }, 1000);
                        return;
                        showCompletedWord();
                    }
                } else {
                    event.target.classList.remove("correct");
                    event.target.classList.add("incorrect");
                }

            });

            // 修改键盘操作事件监听器
            inputBox.addEventListener("keydown", function(event) {
                const index = parseInt(event.target.dataset.index);
                if (event.key === "Backspace") {
                    if (event.target.value === "" && index > 0) {
                        const previousInput = inputContainer.children[index - 1];
                        previousInput.focus();
                        previousInput.value = '';
                        previousInput.classList.remove("correct", "incorrect");
                        
                    } else {
                        event.preventDefault(); // 阻止默认行为
                        event.target.value = '';
                        event.target.classList.remove("correct", "incorrect");

                    }

                } else if (event.key === "ArrowLeft" && index > 0) {
                    inputContainer.children[index - 1].focus();
                } else if (event.key === "ArrowRight" && index < currentWord.length - 1) {
                    inputContainer.children[index + 1].focus();
                } else if (event.key === " ") {
                    if (index < currentWord.length - 1) {
                        inputContainer.children[index + 1].focus();  // 移动到下一个输入框
                    }
                }
            });

            // 聚焦效果
            inputBox.addEventListener("focus", function(event) {
                event.target.classList.add("focused");
            });

            inputBox.addEventListener("blur", function(event) {
                event.target.classList.remove("focused");
            });
        }

        inputContainer.children[0].focus();

        // Add event listener for the skip button
        const skipButton = document.getElementById('skip-button');
        skipButton.addEventListener('click', skipWord);
    }

    function showCompletedWord() {
        inputContainer.innerHTML = "";
        const completedWordDisplay = document.createElement("div");
        completedWordDisplay.textContent = currentWord;
        completedWordDisplay.classList.add("completed-word");
        inputContainer.appendChild(completedWordDisplay);

        // Mark the word as completed and increment the completedWords counter
        wordResults[currentWord] = true;
        completedWords++;
        
        setTimeout(() => {
            wordIndex++;
            initializeWord();
        }, 1500);
    }

    // 初始化第一个单词
    initializeWord();

    function endGame() {
        // Update remaining words to 0 since the game is ending
        document.getElementById('remaining-words').innerText = 'Remaining Words: 0';
        
        // 只保留禁用 skip 按钮
        const skipButton = document.getElementById('skip-button');
        skipButton.disabled = true;
        
        // 禁止输入
        const inputs = document.querySelectorAll('.letter-input');
        inputs.forEach(input => {
            input.disabled = true;
        });

        // 只保留完成图片显示逻辑
        const completionImage = document.getElementById('completion-image');
        if (completedWords >= words.length) {
            showCompletionImage();
        }

        // 更新完成率
        completionRate = (completedWords / words.length).toFixed(2);

        // 准备单词学习记录数据
        const wordLearningRecords = words.map(word => ({
            word: word,
            correct: wordResults[word] === true
        }));

        // 发送游戏结果和单词学习记录到服务器
        fetch('/submit_game_result', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                game_id: game_id,
                game_mode: 'spell',
                score: score,
                completion_rate: completionRate,
                word_results: wordLearningRecords  // 添加单词���习记录
            })
        })
        .then(response => response.json())
        .then(data => {
            console.log('Game result submitted:', data);
        })
        .catch((error) => {
            console.error('Error:', error);
        });

        // 显示单词列表
        showWordList();
    }

    function showCompletionImage() {
        const completionImage = document.getElementById('completion-image');
        completionImage.style.backgroundImage = "url('{{ url_for('static', filename='completed.png') }}')";
        completionImage.classList.add('show');

        // Trigger the animation
        setTimeout(() => {
            completionImage.classList.add('animate');
        }, 50);
    }

    function showWordList() {
        const wordlistContainer = document.getElementById('wordlist-container');
        const wordResultsList = document.getElementById('word-results');
        
        wordlistContainer.style.display = 'block';
        wordResultsList.innerHTML = '';

        words.forEach(word => {
            const listItem = document.createElement('li');
            const wordSpan = document.createElement('span');
            const iconSpan = document.createElement('span');
            
            wordSpan.textContent = word;
            
            iconSpan.className = 'word-result-icon';
            if (wordResults[word]) {
                iconSpan.className += ' correct';
                iconSpan.innerHTML = '&#10004;'; // Checkmark
            } else {
                iconSpan.className += ' incorrect';
                iconSpan.innerHTML = '&#10008;'; // Cross
            }
            
            listItem.appendChild(wordSpan);
            listItem.appendChild(iconSpan);
            wordResultsList.appendChild(listItem);
        });
    }

    // Remove the startTimer() call from here

    // 在 <head> 标签添加 Orbitron 字体
    const link = document.createElement('link');
    link.href = 'https://fonts.googleapis.com/css2?family=Orbitron:wght@400;700&display=swap';
    link.rel = 'stylesheet';
    document.head.appendChild(link);

    // Add the skipWord function
    function skipWord() {
        wordResults[currentWord] = false;
        showSkippedWord();
    }

    function showSkippedWord() {
        inputContainer.innerHTML = "";
        const skippedWordDisplay = document.createElement("div");
        skippedWordDisplay.textContent = currentWord;
        skippedWordDisplay.classList.add("completed-word");
        inputContainer.appendChild(skippedWordDisplay);

        setTimeout(() => {
            wordIndex++;
            initializeWord();
        }, 2000);
    }

    // 保留原来的 playAudio 函数，用于点击播放
    function playAudio(audioUrl, iconElement) {
        console.log("audio-url", audioUrl);
        if (audioUrl) {
            const audio = new Audio(audioUrl);
            
            iconElement.classList.add('playing');
            
            audio.play().catch(error => console.log("Playback prevented:", error));
            
            audio.onended = function() {
                iconElement.classList.remove('playing');
            };
        }
    }

    // 新增：开始游戏的函数
    function startGame() {
        autoPlayEnabled = true;
        document.getElementById('start-game-button').style.display = 'none';
        document.getElementById('blur-overlay').style.opacity = '0';
        setTimeout(() => {
            document.getElementById('blur-overlay').style.display = 'none';
        }, 300); // 等待淡出动画完成后隐藏元素
        initializeWord();
    }
</script>
{% endblock %}